package com.thinkersre.controller;

import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.thinkersre.annotation.LoginRequired;
import com.thinkersre.dao.UserMapper;
import com.thinkersre.entity.Comment;
import com.thinkersre.entity.DiscussPost;
import com.thinkersre.entity.Page;
import com.thinkersre.entity.User;
import com.thinkersre.service.*;
import com.thinkersre.util.HostHolder;
import com.thinkersre.util.ThinkersReConstant;
import com.thinkersre.util.ThinkersReUtil;
//import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/user")
public class UserController implements ThinkersReConstant {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Value("${thinkersre.path.upload}")
    private String uploadPath;
    @Value("${thinkersre.path.domain}")
    private String domain;
    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Resource
    private UserService userService;
    @Resource
    private HostHolder hostHolder;
    @Resource
    private LikeService likeService;
    @Resource
    private FollowService followService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private DiscussPostService discussPostService;
    @Resource
    private CommentService commentService;

    @Value("${qiniu.key.access}")
    private String accessKey;
    @Value("${qiniu.key.secret}")
    private String secretKey;
    @Value("${qiniu.bucket.header.name}")
    private String headerBucketName;
    @Value("${qiniu.bucket.header.url}")
    private String headerBucketUrl;
    @LoginRequired
    @GetMapping("/setting")
    public String getSettingPage(Model model){

        //上传文件名称
        String fileName = ThinkersReUtil.getUUID();
        //设置响应信息
        StringMap policy = new StringMap();
        policy.put("returnBody",ThinkersReUtil.getJSONString(0));
        //生成上传凭证
        Auth auth = Auth.create(accessKey,secretKey);
        String uploadToken = auth.uploadToken(headerBucketName,fileName,3600,policy);

        model.addAttribute("uploadToken",uploadToken);
        model.addAttribute("fileName",fileName);

        return "/site/setting";
    }


    //更新头像路径
    @PostMapping("/header/url")
    @ResponseBody
    public String updateHeaderUrl(String fileName){
        if(StringUtils.isBlank(fileName)){
            return ThinkersReUtil.getJSONString(1,"文件名不能为空.");
        }

        String url = headerBucketUrl + "/" + fileName;
        userService.updateHeader(hostHolder.getUser().getId(),url);

        return ThinkersReUtil.getJSONString(0);

    }





    //废弃
    @LoginRequired
    @PostMapping("/upload")
    public String uploadheaderUrl(MultipartFile headerImage, Model model){
        if(headerImage == null){
            model.addAttribute("error","您还没有选择文件");
            return "/site/setting";
        }
        //获取原始文件名
        String fileName = headerImage.getOriginalFilename();
        //截取后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //判断后缀是否为空
        if(StringUtils.isBlank(suffix)){
            model.addAttribute("error","文件格式不正确");
            return "/site/setting";
        }
        //生成随机文件名
        fileName = ThinkersReUtil.getUUID() + suffix;
        //确定文件存储路径
        File dest = new File(uploadPath+"/"+fileName);
        try {
            headerImage.transferTo(dest);
        } catch (IOException e) {
            logger.error("文件上传失败:"+e.getMessage());
            throw new RuntimeException("文件上传失败,服务器发生异常",e);
        }
        //更新当前用户的头像路径(web访问路径
        //获取到当前用户
        User user = hostHolder.getUser();
        //设置头像url
        String headerUrl = domain + contextPath + "/user/header/" + fileName;
        //更新
        userService.updateHeader(user.getId(),headerUrl);

        return "redirect:/index";
    }




    //废弃
    @GetMapping("/header/{fileName}")
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse httpServletResponse){
        //服务器存放路径
        fileName = uploadPath + "/" + fileName;
        //取出文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //响应图片
        httpServletResponse.setContentType("image/"+suffix);
        try (
                //创建文件输出流
            ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
            //创建文件输入流
            FileInputStream fileInputStream = new FileInputStream(fileName);
                ){
            //创建文件缓冲区
            byte[] buffer = new byte[1024];
            int b = 0;
            //开始读取
            while ((b = fileInputStream.read(buffer)) != -1){
                //一次读从buffer数组中读取0-b个字节
                 servletOutputStream.write(buffer,0,b);
            }
        } catch (IOException e) {
            logger.error("读取头像失败:"+e.getMessage());
//            throw new RuntimeException(e);
        }
    }


    @LoginRequired
    @PostMapping("/updatePassword")
    public String updatePassword(String originalPassword, String newPassword, String confirmPassword, Model model, @CookieValue("ticket") String ticket) {
        if (originalPassword == null) {
            model.addAttribute("originalPasswordMsg", "请输入原始密码!");
            return "site/setting";
        }
        if (newPassword == null) {
            model.addAttribute("newPasswordMsg", "请输入新密码!");
            return "site/setting";
        }
        if (confirmPassword == null) {
            model.addAttribute("confirmPasswordMsg", "请输入新密码!");
            return "site/setting";
        }

        int userId = hostHolder.getUser().getId();
        User user = userMapper.selectById(userId);
        if (!ThinkersReUtil.md5encrypt(originalPassword + user.getSalt()).equals(user.getPassword())) {
            model.addAttribute("originalPasswordMsg", "密码错误!");
            return "/site/setting";
        }
        if (!confirmPassword.equals(newPassword)) {
            model.addAttribute("confirmPasswordMsg", "两次输入的密码不一致!");
            return "site/setting";
        }
        userService.updatePassword(user.getId(), ThinkersReUtil.md5encrypt(newPassword + user.getSalt()));
        userService.logout(ticket);
        return "redirect:/login";

    }




    //个人主页
    @GetMapping("/profile/{userId}")
    public String getProfilePage(@PathVariable("userId")int userId,Model model){
        User user = userService.findUserById(userId);
        if(user == null){
            throw new RuntimeException("该用户不存在");
        }
        //用户
        model.addAttribute("user",user);
        //点赞数量
        int userLikeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("userLikeCount",userLikeCount);

        //关注数量
        long followeeCount = followService.findFolloweeCount(userId,ENTITY_TYPE_USER);
        model.addAttribute("followeeCount",followeeCount);
        //粉丝数量
        long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER,userId);
        model.addAttribute("followerCount",followerCount);
        //是否已关注
        boolean hasFollowed = false;
        if(hostHolder.getUser()!=null){
            hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(),ENTITY_TYPE_USER,userId);
        }
        model.addAttribute("hasFollowed",hasFollowed);



        return "/site/profile";
    }







    /**
     * 查询我的帖子
     */
    @RequestMapping(value = "/myPost/{userId}", method = RequestMethod.GET)
    public String getMyDiscussPost(@PathVariable("userId") int userId, Model model, Page page) {
        page.setPageSize(5);
        page.setPath("/user/myPost/" + userId);
        page.setRowsTotal(discussPostService.findDiscussPostRows(userId));

        User user = userService.findUserById(userId);
        model.addAttribute("user", user);
        model.addAttribute("rows", discussPostService.findDiscussPostRows(userId));

        // 按时间排序
        List<DiscussPost> list = discussPostService.findDiscussPosts(userId, page.getOffset(), page.getPageSize(), 0);
        List<Map<String, Object>> discussPost = new ArrayList<>();
        if (list != null) {
            for (DiscussPost post : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("post", post);

                long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId());
                map.put("likeCount", likeCount);

                discussPost.add(map);
            }
        }
        model.addAttribute("discussPost", discussPost);

        return "/site/my-post";
    }




    /**
     * 查询我的回复
     */
    @RequestMapping(value = "/myComment/{userId}", method = RequestMethod.GET)
    public String getMyComment(@PathVariable("userId") int userId, Model model, Page page) {

        int count = commentService.findCommentCountByUserId(userId, ENTITY_TYPE_POST);
        page.setPageSize(5);
        page.setPath("/user/myComment/" + userId);
        page.setRowsTotal(count);
        model.addAttribute("count", count);

        User user = userService.findUserById(userId);
        model.addAttribute("user", user);

        List<Comment> list = commentService.findCommentsByUserId(userId, ENTITY_TYPE_POST, page.getOffset(), page.getPageSize());
        List<Map<String, Object>> comments = new ArrayList<>();
        if (list != null) {
            for (Comment comment : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("comment", comment);

                DiscussPost post = discussPostService.findDiscusPostById(comment.getEntityId());
                map.put("post", post);

                comments.add(map);
            }
        }
        model.addAttribute("comments", comments);

        return "/site/my-reply";
    }
}
